package com.team.six.bluecatshop.controller;

import com.team.six.bluecatshop.domain.*;
import com.team.six.bluecatshop.mapper.TestYingsheUserMapper;
import com.team.six.bluecatshop.service.*;
import com.team.six.bluecatshop.utils.RedisUtil;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileContext;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.math.BigDecimal;
import java.net.URISyntaxException;
import java.util.*;

@Controller
@RequestMapping("/indent")
public class IndentController {

    @Autowired
    IndentService indentService;
    @Autowired
    ProductService productService;
    @Autowired
    HistoryService historyService;
    @Autowired
    AddressService addressService;
    @Autowired
    CustomerService customerService;
    @Autowired
    SkuService skuService;
    @Autowired
    ShoppingCartService shoppingCartService;
    @Autowired
    ActivityService activityService;
    @Autowired
    MiaoShaService miaoShaService;
    @Autowired
    CommentService commentService;
    @Autowired
    TestYingsheUserService testYingsheUserService;
    @Autowired
    TestYingsheProductService testYingsheProductService;

    @Resource
    private RedisUtil redisUtil;

    private final int BUFF_SIZE = 4096;//设置hdfs的端口
    /**
     * 从购物车下单
     */
    @PostMapping("/deal_indent")
    public String dealOrder(Indent indent, String[] checkboxs, String[] counts, Model model ,HttpServletRequest req,@RequestParam(value = "miaoshaId",defaultValue = "")String miaoshaId){

        HttpSession session=req.getSession();

        //计算总价
        double priceIntent=0.00;
        double priceProduct = 0.00;
        for (String checkbox:checkboxs){
            String[] split = checkbox.split("_");
            if(activityService.findActivityByProductId(split[0])!=null){
                Activity activity = activityService.findActivityByProductId(split[0]);
                priceProduct = activity.getDiscountPrice().doubleValue();
            }
            else{
                priceProduct = productService.findById(split[0]).getProductPrice().doubleValue();
            }
            priceIntent += priceProduct*Integer.parseInt(split[1]);
        }

        System.out.println(priceIntent);

        indent.setIndentPrice(new BigDecimal(priceIntent));//设置总价
        indent.setIndentIdentify(0);//设置订单的identify属性，标记为已提交订单


        indentService.add(indent);//添加一条订单数据

        //将订单中的商品添加到历史购买记录数据中---------------
        for (String checkbox:checkboxs){
            String[] split = checkbox.split("_");
            History history = new History();
            history.setIndentId(indent.getIndentId());
            history.setProductId(split[0]);//从checkbox中拿来的商品id

            //删除购物车中的数据--------------------------
            shoppingCartService.removeByProductIdAndCustomerId(split[0],indent.getCustomerId());
            int count=shoppingCartService.findShoppingCartByCustomerID(split[0]);
            session.setAttribute("count",count);
            //删除购物车中的数据--------------------------

            if(activityService.findActivityByProductId(split[0])!=null){
                Activity activity = activityService.findActivityByProductId(split[0]);
                history.setProductPrice(activity.getDiscountPrice());
            }else{
                history.setProductPrice(productService.findById(split[0]).getProductPrice());
            }
            history.setProductCount(Integer.parseInt(split[1]));
            historyService.add(history);
        }
        //将订单中的商品添加到历史购买记录数据中---------------

        //将用户地址查出用于回显--------------------
        List<Address> address = addressService.findAddressByCustomerId(indent.getCustomerId());
        Customer customerIndent = customerService.findById(indent.getCustomerId());
        //将用户地址查出用于回显--------------------



        session.setAttribute("customerIndent",customerIndent);
        session.setAttribute("indent",indent);
        session.setAttribute("address",address);

        //购买的商品展示模块----------------------------------
        List<History> historyIndents = historyService.findHistoryByIndentId(indent.getIndentId());
        for (History historyIndent:historyIndents){
            Product produceIndent = productService.findById(historyIndent.getProductId());
            produceIndent = productService.setImgToProduct(produceIndent);
            historyIndent.setProduct(produceIndent);
        }
        //购买的商品展示模块---------------------------------

        session.setAttribute("historyIndents",historyIndents);
        return "redirect:shopping-order";
    }
    /**
     * 立刻购买(indent中拿的用户id，history中拿的是商品id、商品购买数量和购买的价格)
     * */
    @RequestMapping("/shopping-pay-rightnow")
    public String shoppingPayRightNow(Indent indent, History history, HttpServletRequest req,Model model){

        //System.out.println("indent: "+indent);
        //System.out.println("history: "+history);
        indent.setIndentIdentify(0);//设置标识表示订单未完成
        indent.setCustomerId(indent.getCustomerId());
        BigDecimal indentCount=new BigDecimal(history.getProductCount());
        BigDecimal iii=history.getProductPrice();
        BigDecimal indentPrice=iii.multiply(indentCount);//计算订单总价
        indent.setIndentPrice(indentPrice);
        indentService.add(indent);

        history.setIndentId(indent.getIndentId());
        historyService.add(history);

        //判断是否是一个秒杀商品-----------------------------------
        String productId = history.getProductId();
        if (miaoShaService.findMiaoShaByProductId(productId)!=null){
            MiaoSha miaoSha = miaoShaService.findMiaoShaByProductId(productId);
            //验证redis中是否还有库存
            if (miaoShaService.verifyCount(miaoSha.getMiaoshaId())) {
                //若有库存，先在redis中减去订单数量 decr("miaosha" + miaoSha.getMiaoshaId(), history.getProductCount());
                redisUtil.decr("miaosha" + miaoSha.getMiaoshaId(),history.getProductCount());
                System.out.println("miaosha"+miaoSha.getMiaoshaId()+"还剩"+redisUtil.get("miaosha" + miaoSha.getMiaoshaId()));
                //在数据库中减去购买数量
                miaoSha.setMiaoshaCount(miaoSha.getMiaoshaCount()-history.getProductCount());
                miaoShaService.updateByPrimaryKey(miaoSha);
            }else{
                System.out.println("没扣库存哦");
                Product product=productService.findById(productId);//根据传来的id找到对应商品
                product=productService.setSkuToProduct(product);
                miaoSha.setProduct(product);
                Date timeEnd = miaoSha.getTimeEnd();
                Date now = new Date();
                if (now.after(timeEnd)){
                    model.addAttribute("msg","late");
                }
                model.addAttribute("miaoSha",miaoSha);
                model.addAttribute("msg","error");
                return "seckillDetails";
            }
        }
        //----------------------------------------
        //将用户地址查出用于回显--------------------
        List<Address> address = addressService.findAddressByCustomerId(indent.getCustomerId());
        Customer customerIndent = customerService.findById(indent.getCustomerId());
        //将用户地址查出用于回显--------------------

        Product produceIndent = productService.findById(history.getProductId());

        produceIndent = productService.setImgToProduct(produceIndent);
        history.setProduct(produceIndent);



        List<History> historyIndents=new ArrayList<>();
        historyIndents.add(history);

        HttpSession session=req.getSession();
        session.setAttribute("historyIndents",historyIndents);
        session.setAttribute("customerIndent",customerIndent);
        session.setAttribute("indent",indent);
        session.setAttribute("address",address);

        return "redirect:shopping-order";
    }

    /**
     * 下单并跳转至结算页面
     * */
    @RequestMapping("/shopping-order")
    public String shoppingOrder(HttpServletRequest req){
        int count = 0;
        HttpSession session=req.getSession();
        Indent indent= (Indent) session.getAttribute("indent");

        List<History> histories = historyService.findHistoryByIndentId(indent.getIndentId());
        /**
         * 下单，减去库存量
         * */
        for (History history : histories){
            String productId = history.getProductId();

            //------------------------------------------------------------------
            //将订单添加进comment表中
            Comment comment = new Comment();
            comment.setProductId(productId);
            comment.setHistoryId(history.getHistoryId());
            Indent historyIndent = indentService.findById(history.getIndentId());
            comment.setCustomerId(historyIndent.getCustomerId());
            int insert = commentService.insert(comment);

            //----------------------------------------------------------------------
            //判断是否是一个秒杀商品,若为普通商品则减少库存
            if (miaoShaService.findMiaoShaByProductId(productId)==null){
                Product product = productService.findById(history.getProductId());
                count = product.getProductCount() - history.getProductCount();
                product.setProductCount(count);
                productService.updateByPrimaryKey(product);
            }

        }

        if (indent.getIndentIdentify()==1){//若订单已提交过
            return "error/404";
        }else if(req.getSession().getAttribute("indent")==null){//若压根没订单
            return "error/404";
        }

        return "shopping-order";
    }

    /**
     * 保存用户选择的收货地址
     * */
    @RequestMapping("/save_address")
    @ResponseBody
    public String saveAddress(Indent indent,HttpSession session){
        session.setAttribute("indent",indent);
        indentService.updateIndentByIndentId(indent);//保存收货地址
        return "success";
    }

    @RequestMapping("/shopping-pay")
    public String shoppingPay(HttpServletRequest req,String IndentPrice){
        System.out.println(IndentPrice);
        if (req.getSession().getAttribute("indent")==null)
        {
          return "error/404";
        }
        HttpSession session=req.getSession();
        session.removeAttribute("customerIndent");
        session.removeAttribute("address");
        session.removeAttribute("historyIndents");

        Indent indent= (Indent) session.getAttribute("indent");
        indent=indentService.findById(indent.getIndentId());
        indent.setIndentPrice(new BigDecimal(IndentPrice));
        indentService.updateByPrimaryKey(indent);
        indent.setIndentIdentify(1);//设置为已完成订单


        session.setAttribute("indent",indent);
        return "shopping-pay";
    }

//    从订单表中删除该订单
    @RequestMapping("/indentDelete")
    @ResponseBody
    public String deleteIndent(@RequestParam String indentId){
        int count = 0;
        List<History> histories = historyService.findHistoryByIndentId(indentId);
        for(History history : histories){
            Product product = productService.findById(history.getProductId());

            String productId = history.getProductId();
            //判断是否是一个秒杀商品
            if (miaoShaService.findMiaoShaByProductId(productId)==null){
                System.out.println("这不是一个秒杀商品");
                count = product.getProductCount() + history.getProductCount();
                product.setProductCount(count);
                productService.updateByPrimaryKey(product);
            }else{
                MiaoSha miaoSha = miaoShaService.findMiaoShaByProductId(productId);
                count = miaoSha.getMiaoshaCount() + history.getProductCount();
                redisUtil.incr("miaosha"+miaoSha.getMiaoshaId(),history.getProductCount());
                miaoSha.setMiaoshaCount(count);
                miaoShaService.updateByPrimaryKey(miaoSha);
                System.out.println("miaosha"+miaoSha.getMiaoshaId()+"还剩"+redisUtil.get("miaosha" + miaoSha.getMiaoshaId()));
            }

            historyService.remove(history.getHistoryId());
        }
        indentService.remove(indentId);
        return "删除成功";
    }
    //未完成订单跳转至购物车页面


    /**
     * 订单详情处理
     */
    @GetMapping("/indentDetails")
    public String indentDetails(Model model,String indentId){
        List<History> histories = historyService.findHistoryByIndentId(indentId);
//        List<Product> products = new ArrayList<>();
        for (History history : histories){
            Comment comment = commentService.selectCommentByHistoryId(history.getHistoryId());

            if(comment.getCommentScore() == null){
                history.setCommentScore(0);
            }else{
                history.setCommentScore(comment.getCommentScore());
            }
            Product product = productService.findById(history.getProductId());
            history.setProductName(product.getProductName());
            history.setProductPostage(product.getProductYoufei());
            history.setComment(comment);
            List<Sku> skus=skuService.findSkuByProductId(product.getProductId());
            if (skus.size() > 0 && skus.get(0)!=null && !skus.get(0).getImgSrc().equals("")){
                history.setImgSrc(skus.get(0).getImgSrc());//从sku中第一个图片作为商品默认展示的图片
            }

        }
        Indent indent = indentService.findById(indentId);
        model.addAttribute("histories",histories);
        model.addAttribute("indent",indent);

        return "indentDetails";
    }

    /**
     * 支付页面
     */
    @GetMapping("/Alipay")
    public String Alipay(HttpSession session){
        int count = 0;
        Indent indent= (Indent) session.getAttribute("indent");
        indent.setIndentIdentify(1);
        indentService.updateByPrimaryKey(indent);

        return "shopping-Alipay";
    }


/**
 * 添加评分并写入日志
 * */
    @GetMapping("/updateCommentScore")
    @ResponseBody
    public String updateScore(Comment comment) throws IOException {
        int i = commentService.updateByPrimaryKeySelective(comment);
        FileSystem fs;
        FileContext fileContext;
        Configuration conf = new Configuration();
        conf.set("fs.defaultFS","hdfs://hadoopmaster:9000");
        fs = FileSystem.get(conf);
        fileContext = FileContext.getFileContext(conf);
        try {
            fs.copyToLocalFile(false,new Path("/team6data"),new Path("./"),true);
        } catch (IOException e) {
            e.printStackTrace();
        }

        Comment comment1 = commentService.findById(comment.getCommentId());
        File file = new File("team6data/u.rating");
        TestYingsheUser testYingsheUser = testYingsheUserService.findTestYingsheUserByCustomerId(comment1.getCustomerId());
        TestYingsheProduct testYingsheProduct = testYingsheProductService.findTestYingsheProductByProductId(comment1.getProductId());
        Customer customer=customerService.findById(comment1.getCustomerId());
        Product product = productService.findById(comment1.getProductId());
        //将未做过评价的商品写入日志和映射表---------------------------------------------------------------------
        if(testYingsheProduct == null){
            //判断商品映射为空，当用户评价时添加映射并写入日志
            //注：训练模型时若没有过评分将无法为该用户推荐
            testYingsheProductService.add(new TestYingsheProduct(comment1.getProductId()));
            File filepro = new File("team6data/u.product");

            TestYingsheProduct yingsheProduct = testYingsheProductService.findTestYingsheProductByProductId(comment1.getProductId());

            Writer out =new FileWriter(filepro,true);

            //u.product 格式：商品映射id+商品id+商品名称+商品价格
            String data= yingsheProduct.getDuctid()+"|"+yingsheProduct.getProductid()+"|"+product.getProductName()+"|"+product.getProductPrice()+"\n";
            out.write(data);
        }
        //将未做过评价的用户写入日志和映射表-------------------------------------------------------------------------
        if(testYingsheUser == null){
            //判断用户映射为空，当用户评价时添加映射并写入日志
            //注：训练模型时若没有过评分将无法为该用户推荐
            testYingsheUserService.add(new TestYingsheUser(comment1.getCustomerId()));
            File fileuser = new File("team6data/u.user");
            TestYingsheUser user = testYingsheUserService.findTestYingsheUserByCustomerId(comment1.getCustomerId());
            Writer out =new FileWriter(fileuser,true);

            //u.user 格式：用户映射id+用户id+用户的昵称+电话+邮箱+真实姓名
            String data= user.getUserid()+"|"+user.getCustomerid()+"|"+customer.getCustomerNickname()+"|"+customer.getCustomerPhone()+"|"+customer.getCustomerEmail()+"|"+customer.getCustomerName()+"\n";
            out.write(data);
        }
        //更新评分的日志--------------------------------------------------------------------------
        Writer out =new FileWriter(file,true);
        //u.rating 格式：用户映射id+商品映射id+商品评分+评分id
        String data= testYingsheUserService.findTestYingsheUserByCustomerId(comment1.getCustomerId()).getUserid()+"|"+testYingsheProduct.getDuctid()+"|"+comment1.getCommentScore()+"|"+comment1.getCommentId()+"\n";
        out.write(data);
        out.close();
        try {
            fs.delete(new Path("/team6data"), true);
            fs.copyFromLocalFile(false,new Path("team6data"),new Path("/team6data"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "success";
    }

}
